<template>
  <div>
    <t-dialog
      header="添加规则"
      body="水平居中显示的对话框"
      :visible="isshow"
      @close="onReset"
      type="reset"
      :footer="false"
      width="800px"
    >
      <dk-divider style="margin: 10px 0"></dk-divider>
      <t-form
        ref="form"
        :rules="FORM_RULES"
        :data="formData"
        :colon="true"
        reset-type="initial"
        @reset="onReset"
        @submit="onSubmit"
        scrollToFirstError="smooth"
        label-width="140px"
      >
        <t-form-item label="意向标签备注" name="knowledgename">
          <t-input
            v-model="formData.knowledgename"
            placeholder="请输入意向标签备注"
            @enter="onEnter"
          ></t-input>
        </t-form-item>

        <t-form-item label="意向标签等级" name="questionmethods">
          <t-select
            v-model="formData.questionmethods"
            :options="ScenemsgOptions"
            placeholder="请选择意向标签等级"
          >
          </t-select>
        </t-form-item>
        <template v-for="(item, index) in formData.answerarr" :key="item.id">
          <t-form-item
            :label="'标签规则' + (index + 1)"
            :name="'answerarr' + index"
          >
            <div style="display: flex; flex-direction: column; width: 100%">
              <div class="delsvgbox">
                <div></div>
                <t-button
                  variant="text"
                  @click="deleteitem(item.id, item.afteranswer)"
                >
                  <icon-svg
                    style="width: 14px; height: 14px"
                    name="icon-shiDelete"
                  ></icon-svg>
                </t-button>
              </div>
              <div class="huidabox">
                <t-select
                  v-model="item.afteranswer"
                  :options="filteredOptions(item.afteranswer)"
                  @change="updateSelectedOptions"
                  style="width: 120px"
                >
                </t-select>
                <div class="optionitembox" v-show="item.afteranswer == 0">
                  <t-select
                    v-model="item.Comparison"
                    :options="Comparisonoptions"
                    style="width: 120px"
                  >
                  </t-select>
                  <t-input-number
                    v-model="item.mincall"
                    theme="column"
                    decimalPlaces="0"
                    min="1"
                    :input-props="{ tips: '最小值为1' }"
                    style="width: 70px"
                  />
                  <span style="width: 40px; text-align: center">次~</span>
                  <t-input-number
                    v-model="item.maxcall"
                    theme="column"
                    allowInputOverLimit="true"
                    decimalPlaces="0"
                    min="1"
                    :input-props="{ tips: '最小值为1' }"
                    style="width: 70px"
                  />
                  <span style="width: 20px; text-align: center">次</span>
                </div>

                <div class="optionitembox" v-show="item.afteranswer == 1">
                  <t-select
                    v-model="item.Comparison"
                    :options="Comparisonoptions"
                    style="width: 120px"
                  >
                  </t-select>
                  <t-input-number
                    v-model="item.mincall"
                    theme="column"
                    min="1"
                    decimalPlaces="0"
                    :input-props="{ tips: '最小值为1' }"
                    style="width: 70px"
                  />
                  <span style="width: 40px; text-align: center">次~</span>
                  <t-input-number
                    v-model="item.maxcall"
                    theme="column"
                    min="1"
                    decimalPlaces="0"
                    :input-props="{ tips: '最小值为1' }"
                    style="width: 70px"
                  />
                  <span style="width: 20px; text-align: center">次</span>
                </div>

                <div class="optionitembox" v-show="item.afteranswer == 2">
                  <t-textarea
                    v-model="item.answer"
                    :maxlength="100"
                    placeholder="请输入关键词"
                  />
                  <t-select
                    v-model="item.Comparison"
                    :options="Comparisonoptions"
                    style="width: 120px"
                  >
                  </t-select>
                  <t-input-number v-model="item.num" min="1" :input-props="{ tips: '最小值为1' }"/>
                </div>
              </div>
            </div>
          </t-form-item>
          <dk-divider style="margin: 10px 0"></dk-divider>

        </template>
        <t-form-item >
          <t-button @click="jia" style="width: 100px">增加标签规则</t-button>
        </t-form-item>
        

        <t-form-item class="buttonbut">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset"
              >取消</t-button
            >
            <t-button theme="primary" type="submit">提交</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>
    
<script setup>
import { ref, defineProps, reactive, watchEffect } from "vue";
import { nanoid } from "nanoid";
import { MessagePlugin } from "tdesign-vue-next";
import { getcreatetask } from "@/api/callOutTasks/index.js";
import {
  Comparisonoptions,
  ScenemsgOptions,
} from "../formcolumn/knowledgeBase";

const props = defineProps({
  // 默认选中的部门id
  isshow: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["event"]);
// 标签规则选项
const leablerousedata = ref([
  { label: "对话轮次", value: "0", disabled: false },
  { label: "通话时长", value: "1", disabled: false },
  { label: "触发关键词", value: "2", disabled: false },
]);
const leablerousearr = ref([]);

const formData = ref({
  knowledgename: "", // 意向标签备注
  questionmethods: "", // 意向标签等级
  interrupt: false, // 是否允许打断
  intentionlable: "", // 意向标签
  customizationlable: "", // 自定义标签
  answerarr: [], // 标签规则
});

const form = ref(null);
//   校验
const FORM_RULES = ref({
  knowledgename: [{ required: true, message: "请输入意向标签备注" }],
  questionmethods: [{ required: true, message: "请选择意向标签等级" }],
  //   Scenemsg: [{ required: true, message: "请选择场景信息" }],
});
// 选择标签规则
const selectedOptions = ref([]);

const updateSelectedOptions = () => {
  selectedOptions.value = formData.value.answerarr.map(
    (item) => item.afteranswer
  );
};

const filteredOptions = (currentValue) => {
  return leablerousedata.value.map((option) => ({
    ...option,
    disabled:
      selectedOptions.value.includes(option.value) &&
      option.value !== currentValue,
  }));
};

// 添加一个答案
const jia = () => {
  if (formData.value.answerarr.length < 3) {
    formData.value.answerarr.push(
      {
        id: nanoid(),
        num: 1, //次数
        mincall: 1, //小次数
        maxcall: 1, // 大次数
        Comparison: 4, //比较
        answer: "", //触发关键词input
        afteranswer: "",
      } //标签规则下拉
    );
  } else {
    MessagePlugin.warning("最多添加三个标签规则");
  }
};
// 删除一个答案
const deleteitem = (id, optionval) => {
  formData.value.answerarr = formData.value.answerarr.filter((item) => {
    return item.id !== id;
  });
  updateSelectedOptions();
};
//取消
const onReset = () => {
  //   MessagePlugin.success("重置成功");
  formData.value.answerarr =[]
  form.value.reset();
  emit("event", false);
};
//提交
const onSubmit = async ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success("提交成功");
    // emit('event', false);
    console.log(formData.value);
    // const res = await getcreatetask(formData);
    // console.log(res);
  } else {
    console.log("Validate Errors: ", firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

watchEffect(() => {
  for (let i = 0; i < formData.value.answerarr.length; i++) {
    let dataobj = ref({});
    dataobj.value = {
      ...dataobj.value,
      ...{ ["answerarr" + i]: formData.value.answerarr[i].answer },
    };
    formData.value = { ...formData.value, ...dataobj.value };
    let obj = ref({});
    obj.value = {
      ...obj.value,
      ...{
        ["answerarr" + i]: [
          {
            validator: (val) => {
              if (formData.value.answerarr[i]?.afteranswer == "") {
                return false;
              }
              if (/^[1-9]\d*$/.test(formData.value.answerarr[i]?.mincall) == false) {
                return false;
              }
              if (/^[1-9]\d*$/.test(formData.value.answerarr[i]?.maxcall) == false) {
                return false;
              }
              if (/^[1-9]\d*$/.test(formData.value.answerarr[i]?.num) == false) {
                return false;
              }
              if (
                formData.value.answerarr[i]?.answer == "" &&
                formData.value.answerarr[i]?.afteranswer == "2"
              ) {
                return false;
              }

              return true;
            },
            required: true,
            message: `请把标签规则${i + 1}填写完整,或删除标签规则${i + 1}`,
            trigger: "change",
          },
        ],
      },
    };
    FORM_RULES.value = { ...FORM_RULES.value, ...obj.value };
  }
});

// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter = (_, { e }) => {
  e.preventDefault();
};
</script>
    
    <style lang="scss" scoped>
.buttonbut {
  display: flex;
  justify-content: space-between;
}
.outtimecla {
  display: flex;
  flex-direction: column;
  .outtimecla_item {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
  }
}
.delsvgbox {
  display: flex;
  justify-content: space-between;
  //   padding: 8px;
}
.huidabox {
  display: flex;
  align-items: center;
  padding: 8px 0;
  span {
    width: 60px;
    // text-align: right;
  }
}
.optionitembox {
  display: flex;
  align-items: center;
}
:deep(.t-dialog__ctx .t-dialog) {
  max-height: 90%;
  overflow-y: scroll;
}
</style>
    